package com.github.houbb.spi.bs;

import com.github.houbb.heaven.util.common.ArgUtil;
import com.github.houbb.spi.api.impl.ExtensionLoader;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * spi 引导类
 * @author binbin.hou
 * @since 0.0.1
 */
public final class SpiBs {

    private SpiBs(){}

    /**
     * 拓展加载类 map
     * @since 0.0.1
     */
    private static final Map<Class, ExtensionLoader> EX_LOADER_MAP = new ConcurrentHashMap<>();

    /**
     * 加载实例
     * @param clazz 类
     * @param <T> 泛型
     * @return 结果
     * @since 0.0.1
     */
    @SuppressWarnings("unchecked")
    public static <T> ExtensionLoader<T> load(Class<T> clazz) {
        ArgUtil.notNull(clazz, "clazz");

        ExtensionLoader extensionLoader = EX_LOADER_MAP.get(clazz);
        if(EX_LOADER_MAP.get(clazz) != null) {
            return extensionLoader;
        }

        // DLC
        synchronized (EX_LOADER_MAP) {
            extensionLoader = EX_LOADER_MAP.get(clazz);
            if(extensionLoader == null) {
                extensionLoader = new ExtensionLoader(clazz);

                // cached
                EX_LOADER_MAP.put(clazz, extensionLoader);
            }
        }

        return extensionLoader;
    }

}
